'use strict';

module.exports = {
  /*
    * 根据url解析模版路径
    * @param string req_url 要解析的URL
    * @param string ext 模版后缀
    * return string
    * For: this.ctx.view_path('http://localhost:7001/admin/index/login') => admin/index/login.html
    * */
  view_path(req_url, ext = '.html') {
    let path = '';
    if (!req_url) {
      path = this.request.path;
    } else if (/^http/.test(req_url)) { // 判断是否为url形式
      const obj_url = new URL(req_url);
      path = obj_url.pathname;
    } else {
      path = req_url;
    }
    return path.substr(1) + ext;
  },

  /*
    * 错误页面
    * @param string msg 错误信息
    * @param string url 跳转的url
    * @param int wait 等待跳转的时间(s)
    * @param string path 页面模板路径
    * return string
    * For: this.ctx.error('无权访问')
    * */
  async error(msg, url = '', wait = 2, path = '/admin/public/error') {
    const jump_url = url ? url : 'javascript:history.back(-1);';
    const error = msg;
    return this.render(this.view_path(path), { jump_url, error, wait });
  },

  /*
    * 成功页面
    * @param string msg 提示信息
    * @param string url 跳转的url
    * @param int wait 等待跳转的时间(s)
    * @param string path 页面模板路径
    * return string
    * For: this.ctx.success('编辑成功')
    * */
  async success(msg, url = '', wait = 2, path = '/admin/public/error') {
    const jump_url = url ? url : 'javascript:history.back(-1);';
    const message = msg;
    return this.render(this.view_path(path), { jump_url, message, wait });
  },

  /*
    * ip地址查询
    * @param string ip IP
    * return obj
    * For: this.ctx.get_ip_info('27.154.27.152') => {province:'福建',city:'厦门',area:'XX',isp:'电信'}
    * */
  async get_ip_info(ip) {
    if (!this.helper.check_ip(ip)) {
      ip = this.helper.check_ip(this.ip) ? this.ip : '127.0.0.1';
    }
    const url = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip;
    const res = await this.curl(url, { method: 'get', dataType: 'json', timeout: 4000 });
    const info = {};
    if (res.status == 200) {
      const content = res.data;
      if (content.code == 0) {
        info.province = content.data.region;
        info.city = content.data.city;
        info.area = content.data.county;
        info.isp = content.data.isp;
      }
    }
    return info;
  },

};

